﻿using System;
using System.Threading;

public class AlarmClock
{
    private readonly AutoResetEvent tickEvent = new AutoResetEvent(false);
    private readonly AutoResetEvent alarmEvent = new AutoResetEvent(false);
    private bool running = false;

    public event EventHandler Tick;
    public event EventHandler Alarm;

    public void Start()
    {
        running = true;
        Thread tickThread = new Thread(TickHandler);
        Thread alarmThread = new Thread(AlarmHandler);
        tickThread.Start();
        alarmThread.Start();
    }

    public void Stop()
    {
        running = false;
        tickEvent.Set();
        alarmEvent.Set();
    }

    private void TickHandler()
    {
        while (running)
        {
            Thread.Sleep(1000); // 1秒钟嘀嗒一次
            Console.WriteLine("Tick");
            OnTick();
            tickEvent.Set();
        }
    }

    private void AlarmHandler()
    {
        while (running)
        {
            alarmEvent.WaitOne();
            Console.WriteLine("Alarm is ringing!");
            OnAlarm();
        }
    }

    protected virtual void OnTick()
    {
        Tick?.Invoke(this, EventArgs.Empty);
    }

    protected virtual void OnAlarm()
    {
        Alarm?.Invoke(this, EventArgs.Empty);
    }

    public void TriggerAlarm()
    {
        alarmEvent.Set();
    }
}

class Program
{
    static void Main(string[] args)
    {
        AlarmClock clock = new AlarmClock();
        clock.Tick += (sender, e) => Console.WriteLine("Tick event");

        // 订阅Alarm事件并在触发时显示消息
        clock.Alarm += (sender, e) => Console.WriteLine("Alarm event");

        clock.Start();

        // 模拟触发响铃
        clock.TriggerAlarm();

        Console.WriteLine("Press 's' to stop the clock");
        while (true)
        {
            if (Console.ReadKey().KeyChar == 's')
            {
                clock.Stop();
                break;
            }
        }
    }
}
